package com.crm.common.util;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author yincuimei
 * @Date 2021/4/8 11:39
 */
@Slf4j
public class FileUtil {

    /**
     * 生成文件绝对路径
     * @param fileName    ---文件原名
     * @param targetPath  ---目标路径
     * @return
     */
    public static String generateFilePath(long time,String fileName,String targetPath){
        String filePathStr = new StringBuilder(PathUtil.getBasePath()+ targetPath)
                .append(time)
                .append(fileName)
                .toString();

        makeDirPath(targetPath);
        return filePathStr;
    }

     /**
     * 创建目标路径
     */
     private static void makeDirPath(String targetPath) {
         String realFileParentPath = PathUtil.getBasePath() + targetPath;
         File dirPath = new File(realFileParentPath);
         if (!dirPath.exists()) {
             dirPath.mkdirs();
         }
     }
     
    /***
     * @Description: Word文件转PDF文件
     * @Param:inPath word文件的存储路径
     * @Param:outPath PDF文件的存储路径
     * @Author: luojie
     * @Date: 2021/4/11 15:01
     */ 
    public static void doc2pdf(String inPath, String outPath) {

        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return;
        }
        try {
            //log.info("PDF转换开始");
            //开始时间
            long old = System.currentTimeMillis();
            //获取文件
            File file = new File(outPath);
            //获取文件流
            FileOutputStream os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            Document doc = new Document(inPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
            doc.save(os, SaveFormat.PDF);
            os.close();
            //结束时间
            //long now = System.currentTimeMillis();
            //log.info("PDF转换结束 共耗时：" + ((now - old) / 1000.0) + "秒");
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * 去除水印
     *
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = FileUtil.class.getClassLoader().getResourceAsStream("License.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
